<template>
  <div class="my-custom" v-loading="loading" element-loading-text="加载中...">
    <div class="my-custom-head-box">
      <iframe ref="resizeFrame" class="resizeFrame" frameborder="0" id="AccElFormRef"></iframe>
      <div class="my-custom-head">
        <!--客户类型  -->
        <div class="search-top">
          <el-select style="width: 120px" class="search-top-select" size="small" v-model="searchForm.is_my"
            placeholder="请选择">
            <el-option label="我的客户" :value="1" />
            <el-option label="下属客户" :value="2" />
          </el-select>
          <div class="tab-box">
            <el-tabs v-model="searchForm.cType" class="demo-tabs" @tab-click="cTypeChange">
              <el-tab-pane label="全部" name=""></el-tab-pane>
              <el-tab-pane v-for="item in setupList" :label="item.name" :name="item.name"></el-tab-pane>
            </el-tabs>
          </div>
        </div>
        <!-- 客户属性 -->
        <div class="search-center">
          <el-tag v-for="item in attributeList" class="attribute-item"
            :effect="s_attrId == item.name ? 'dark' : 'light'" @click="selectAttrFun(item)" round>
            {{ item.name ? item.name : "全部" }}
          </el-tag>
        </div>
        <!-- 其他搜索条件 -->
        <!--搜索-上  -->
        <div v-show="complexType">
          <el-form class="demo-searchForm">
            <el-form-item label="所在地区">
              <el-tree-select default-expand-all node-key="id" filterable v-model="searchForm.region" :data="areaTree"
                check-strictly clearable :render-after-expand="false" :props="{
                  label: 'name',
                  children: 'sub',
                }" style="width: 220px !important" placeholder="所在地区">
              </el-tree-select>
            </el-form-item>
            <el-form-item label="客户来源">
              <el-tag class="attribute-item" :effect="!s_source || s_source == 'null-0' ? 'light' : 'plain'" round
                @click="sourceFun({ id: 'null-0' })">
                全部
              </el-tag>
              <el-tag class="attribute-item" @click="sourceFun(item)" v-for="item in sourceList" round
                :effect="s_source == item.id ? 'light' : 'plain'">
                {{ item.name }}
              </el-tag>
            </el-form-item>
            <el-form-item label="销售阶段">
              <el-tag class="attribute-item" :effect="!s_stage || s_stage == 'null-0' ? 'light' : 'plain'" round
                @click="stageFun({ id: 'null-0' })">
                全部
              </el-tag>
              <el-tag class="attribute-item" @click="stageFun(item)" v-for="item in stageList" round
                :effect="s_stage == item.id ? 'light' : 'plain'">
                {{ item.name }}
              </el-tag>
            </el-form-item>
            <el-form-item label="客户标签">
              <el-tree-select style="width: 220px" node-key="id" v-model="searchForm.label" :data="labelList" multiple
                :props="{
                  label: 'name',
                  children: 'children',
                }" :render-after-expand="false" show-checkbox />
            </el-form-item>
            <el-form-item label=" 销 售">
              <el-tree-select default-expand-all node-key="id" filterable v-model="searchForm.owner_uid"
                :data="userOptions" check-strictly :render-after-expand="false" :props="{
                  label: 'name',
                }" style="width: 220px; margin-left: 25px" placeholder="选择销售" clearable>
              </el-tree-select>
            </el-form-item>
          </el-form>
        </div>
        <!--搜索-下  -->
        <el-form inline class="demo-searchForm">
          <el-form-item>
            <el-select v-model="searchForm.srch_type" placeholder="请选择">
              <el-option label="客户名称" value="客户名称" />
              <el-option label="电话号码" value="电话号码" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-input v-model="searchForm.keyword" placeholder="请输入查询内容" />
          </el-form-item>
          <el-form-item>
            <el-date-picker v-model="searchForm.time" type="datetimerange" value-format="YYYY-MM-DD HH:mm:ss"
              range-separator="至" start-placeholder="分配开始时间" end-placeholder="分配结束时间" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="searchFun">查询</el-button>
            <el-button @click="resetFun">重置</el-button>
            <!-- <el-button type="primary">导出</el-button> -->
            <el-button type="primary" @click="complexFun" link>复杂搜索
              <IEpArrowDown v-show="!complexType" style="margin-left: 5px" />
              <IEpArrowUp v-show="complexType" style="margin-left: 5px" />
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      <div>
        <el-form inline>
          <el-form-item>
            <el-button type="primary" @click="addPool">
              <template #icon>
                <el-icon>
                  <IEpPlus />
                </el-icon>
              </template>
              增加
            </el-button>
            <el-button @click="uploadFun">
              <template #icon>
                <el-icon>
                  <IEpUpload />
                </el-icon>
              </template>
              导入
            </el-button>
            <el-button type="success" @click="downloadFun">
              <template #icon>
                <el-icon>
                  <IEpDownload />
                </el-icon>
              </template>
              导出
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <div class="my-custom-content">
      <el-table :data="tableData" border :height="store.tableHeight - headerHeight + 10"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column label="ID" prop="id" />
        <el-table-column v-for="item in tableHead" :label="item.name">
          <template #default="{ row }">
            <el-button @click="customDetailFun(row)" v-if="item.field == 'name'" type="primary" link>
              {{ row[item.field] }}
            </el-button>
            <span v-else>
              {{ row[item.field] }}
            </span>
          </template>
        </el-table-column>

        <el-table-column label="创建时间" prop="created_at" width="170" />
        <el-table-column label="创建人姓名" prop="created_user" />
        <el-table-column label="操作" width="120" align="center">
          <template #default="{ row }">
            <el-button type="primary" link @click="updateOpen(row)">
              编辑
            </el-button>
            <el-button type="danger" link @click="delFun(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="my-custom-content-pagination">
        <div>
          <el-button type="success" :disabled="selectData.length == 0" @click="allShareFun">
            批量共享
          </el-button>
          <el-button type="primary" :disabled="selectData.length == 0" @click="allObtainFun">
            批量转移
          </el-button>
          <el-button type="warning" :disabled="selectData.length == 0" @click="allReturnFun">批量退回</el-button>
          <el-button type="danger" :disabled="selectData.length == 0" @click="allDelFun">批量删除</el-button>
          <el-dropdown split-button type="primary" style="margin-left: 10px;" @click="handleClick"
            @command="handleCommandClick">
            批量标记{{ own_type }}
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="临时客户">临时客户</el-dropdown-item>
                <el-dropdown-item command="私有客户">私有客户</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
        <el-pagination v-model:currentPage="currentPage" v-model:page-size="pageSize" :page-sizes="[20, 50, 100, 200]"
          layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </div>
  </div>
  <!-- 新增 -->
  <addDialog ref="addDialogRef" @refreshTable="refreshTable" />
  <!-- 详情 -->
  <drawerPage @refreshParent="refreshParent" ref="drawerPageRef" />
  <!-- 上传 -->
  <uploadPage ref="uploadPageRef" @updateList="updateList" />
  <!-- 批量 -->
  <batchPage ref="batchPageRef" @refreshList="updateList" />
</template>
<script setup>
import { useCounterStore } from "@/stores/counter.js";
import {
  listApi,
  detailApi,
  deleteApi,
  exportApi,
  unObtainApi,
} from "@/plugins/api/customer/manage/my";

// 类型设置
import { listApi as setupListApi } from "@/plugins/api/customer/setup/first";
// 客户属性
import { listApi as thirdListApi } from "@/plugins/api/customer/setup/third";
// 地区
import { listApi as areaApi } from "@/plugins/api/shopping/area";
// 字典查询
import { listApi as dictApi } from "@/plugins/api/system/dict";
// 客户标签
import { listApi as labelApi } from "@/plugins/api/customer/setup/fourth";
// 销售
import { treePersonApi } from "@/plugins/api/system/user";
//
import addDialog from "./components/DialogMyCustom.vue";
//
import drawerPage from "./components/DrawerCustom.vue";
//
import uploadPage from "./components/Pool-UploadFile.vue";
// 批量
import batchPage from "./components/MyBatch.vue";

// 销售
let userOptions = ref([]);
function getUsers() {
  treePersonApi().then((res) => {
    userOptions.value = res;
  });
}
const own_type = ref()
const handleClick = () => {
  console.log(`批量标记 ${own_type.value}`)
}
const handleCommandClick = (e) => {
  own_type.value = e
  console.log(e)
}



const store = useCounterStore();
//
let resizeFrame = ref(null);
let headerHeight = ref(0);
function formAddEvent() {
  if (resizeFrame.value) {
    resizeFrame.value.contentWindow.addEventListener("resize", () => {
      nextTick(() => {
        let dom = document.getElementById("AccElFormRef");
        let height = dom.clientHeight;
        headerHeight.value = height;
      });
    });
  }
}
// 客保设置
let setupList = ref([
  {
    name: "私有客户",
  },
  {
    name: "临时客户",
  },
  {
    name: "无效客户",
  },
  {
    name: "我共享的客户",
  },
  {
    name: "共享给我的客户",
  },
]);
function getSetupListApi() {
  setupListApi().then((data) => {
    setupList.value = data;
  });
}
function cTypeChange(data) {
  let name = data.props.name;
  searchForm.value.cType = name;
  searchFun();
}
// 复杂搜索
let complexType = ref(false);
function complexFun() {
  complexType.value = !complexType.value;
}
// 所在地区
let areaTree = ref([]);
function getArea() {
  loading.value = true;
  areaApi({}).then((data) => {
    areaTree.value = data;
  });
}
// 客户属性
let attributeList = ref([
  {
    name: "",
  },
  {
    name: "今日新增",
  },
  {
    name: "计划今日跟进",
  },
  {
    name: "计划本周跟进",
  },
  {
    name: "计划本月跟进",
  },
  {
    name: "本周已跟进",
  },
  {
    name: "本月已跟进",
  },
  {
    name: "逾期未跟进",
  },
  {
    name: "商机客户",
  },
  {
    name: "成交客户",
  },
]);
let s_attrId = ref("");
function selectAttrFun(row) {
  s_attrId.value = row.name;
  searchForm.value.aType = row.name;
  searchFun();
}
function getThirdListApi() {
  thirdListApi().then((data) => {
    attributeList.value = data.filter((item) => {
      return item.status == 1;
    });
  });
}
// 客户来源
let sourceList = ref([]);
let s_source = ref("");
function sourceFun(row) {
  s_source.value = row.id;
  if (row.id !== "null-0") {
    searchForm.value.source = row.name;
  } else {
    searchForm.value.source = "";
  }
}
// 销售阶段
let stageList = ref([]);
let s_stage = ref("");
function stageFun(row) {
  s_stage.value = row.id;
  if (row.id !== "null-0") {
    searchForm.value.deal_status = row.name;
  } else {
    searchForm.value.deal_status = "";
  }
}
// 获取字典项
function getDictionary(dict_id) {
  return new Promise((resolve, reject) => {
    dictApi({ dict_id: dict_id }).then((data) => {
      resolve(data);
    });
  });
}
// 客户标签
let labelList = ref([]);
function getLabel() {
  labelApi().then((data) => {
    labelList.value = data;
  });
}
// 详情
let drawerPageRef = ref(null);
function customDetailFun(row) {
  drawerPageRef.value.initFun(row, true, "my");
}

//
let loading = ref(false);
let searchForm = ref({
  cType: "",
});
let searchData = ref({});
let tableHead = ref([]);
let tableData = ref([]);
let selectData = ref([]);
function handleSelectionChange(val) {
  selectData.value = val.map((item) => {
    return item.id;
  });
}
function refreshParent() {
  getData();
}
//
function searchFun() {
  let obj = { ...searchForm.value };
  if (searchForm.value.time) {
    obj.start_time = searchForm.value.time[0];
    obj.end_time = searchForm.value.time[1];
  }
  searchData.value = { ...obj };
  tableData.value = [];
  currentPage.value = 1;
  getData();
}
// 重置
function resetFun() {
  searchForm.value = {
    cType: "",
  };

  searchData.value = {};
  tableData.value = [];
  currentPage.value = 1;
  s_attrId.value = "";
  s_source.value = "";
  s_stage.value = "";
  getData();
}
// 分页
const currentPage = ref(1);
const pageSize = ref(20);
const total = ref(0);
const handleSizeChange = (val) => {
  pageSize.value = val;
  selectData.value = [];
  getData();
};
const handleCurrentChange = (val) => {
  currentPage.value = val;
  selectData.value = [];
  getData();
};
function getData() {
  let obj = {
    page: currentPage.value,
    pageSize: pageSize.value,
  };
  obj = { ...obj, ...searchData.value };
  loading.value = true;
  listApi(obj)
    .then((res) => {
      tableHead.value = res.fields.filter((item) => {
        return item.in_list == 1;
      });
      tableData.value = res.list;
      total.value = res.page.total;
      loading.value = false;
    })
    .catch(() => {
      loading.value = false;
    });
}
function refreshTable() {
  selectData.value = [];
  getData();
}
// 增加
let addDialogRef = ref(null);
function addPool() {
  addDialogRef.value.initFun("add");
}
// 编辑
function updateOpen(row) {
  detailApi({
    id: row.id,
  }).then((res) => {
    addDialogRef.value.initFun("update", res.customer || {});
  });
}
// 删除
function delFun(row) {
  ElMessageBox.confirm("确认删除，是否继续?", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      deleteApi({
        id: row.id,
      }).then(() => {
        ElMessage({
          type: "success",
          message: "删除成功！",
        });
        getData();
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消。",
      });
    });
}

// 批量转移
let batchPageRef = ref(null);
function allObtainFun(row) {
  let str = selectData.value.join(",");
  batchPageRef.value.initFun("zhuanyi", { id: str });
}

// 批量共享
function allShareFun(row) {
  let str = selectData.value.join(",");
  batchPageRef.value.initFun("share", { id: str });
}

// 批量删除
function allDelFun() {
  ElMessageBox.confirm("确认删除选中的数据，是否继续?", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      let str = selectData.value.join(",");
      deleteApi({
        id: str,
      }).then(() => {
        ElMessage({
          type: "success",
          message: "删除成功！",
        });
        selectData.value = [];
        getData();
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消。",
      });
    });
}
// 批量退回
function allReturnFun() {
  ElMessageBox.confirm("确认退回选中的数据，是否继续?", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      let str = selectData.value.join(",");
      unObtainApi({
        id: str,
      }).then(() => {
        ElMessage({
          type: "success",
          message: "操作成功！",
        });
        selectData.value = [];
        getData();
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消。",
      });
    });
}
// 导入
let uploadPageRef = ref(null);
function uploadFun() {
  uploadPageRef.value.initFun();
}
function updateList() {
  getData();
}
// 导出
function downloadFun() {
  let obj = { ...searchForm.value };
  if (searchForm.value.time) {
    obj.start_time = searchForm.value.time[0];
    obj.end_time = searchForm.value.time[1];
  }
  searchData.value = { ...obj };
  exportApi(obj).then((res) => {
    const url = window.URL.createObjectURL(new Blob([res]));
    const link = document.createElement("a");
    link.href = url;
    link.setAttribute("download", "私有客户.xlsx");
    document.body.appendChild(link);
    link.click();
  });
}
//
onMounted(() => {
  // getSetupListApi();
  getData();
  // getThirdListApi();
  getArea();
  getDictionary(3).then((data) => {
    sourceList.value = data;
  });
  getDictionary(7).then((data) => {
    stageList.value = data;
  });
  getLabel();
  formAddEvent();
  getUsers();
});
</script>
<style lang="scss" scoped>
.my-custom {
  width: 100%;
  height: 100%;

  .my-custom-head-box {
    position: relative;

    .resizeFrame {
      position: absolute;
      z-index: -1;
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
    }
  }

  .my-custom-head {
    white-space: nowrap;

    .search-top {
      display: flex;
      width: 100%;
      overflow: hidden;
      overflow-x: auto;

      position: relative;

      &::before {
        position: absolute;
        content: "";
        width: 100%;
        border-bottom: 2px solid #e4e7ed;
        left: -160px;
        bottom: 14px;
      }

      >.search-top-select {
        align-self: center;
        margin-bottom: 13px;
      }

      >.tab-box {
        align-self: center;
        margin-left: 20px;
        width: calc(100% - 140px);
      }
    }

    .search-center {
      width: 100%;
      white-space: wrap;
      margin-bottom: 10px;
    }

    .attribute-item {
      margin-right: 5px;
      margin-bottom: 5px;
      cursor: pointer;
      user-select: none;
    }
  }

  .my-custom-content-pagination {
    display: flex;
    justify-content: space-between;
    margin-top: 10px;
  }
}
</style>
